package cn.jeasy.core.bean.support;

import java.lang.annotation.Annotation;
import java.util.List;

/**
 * 类扫描工具
 * @author Fred
 *
 */
public class ClassScanner {
	private static ClassScanner instance=new ClassScanner();
	private ClassScanner(){}
	
	public synchronized static ClassScanner getInstance(){
		return instance;
	}
	
	/**
	 * 包名匹配的普通类加载
	 * @param packageName
	 * @return
	 */
    public List<Class<?>>  getClassList(String packageName) {
        return new AbstractScanner(packageName) {
            @Override
            public boolean checkAddClass(Class<?> cls) {
                String className = cls.getName();
                String pkgName = className.substring(0, className.lastIndexOf("."));
                return pkgName.startsWith(packageName);
            }
        }.getClassList();
    }

    /**
     * 包名和注解都匹配类加载
     * @param packageName
     * @param annotationClass
     * @return
     */
    public List<Class<?>> getClassListByAnnotations(String packageName, final Class<? extends Annotation>... annotations) {
        return new AbstractScanner(packageName) {
            @Override
            public boolean checkAddClass(Class<?> cls) { 
            	for(Class<? extends Annotation> a:annotations){
            		if(cls.isAnnotationPresent(a))	return true;
            	}
            	return false;
            }
        }.getClassList();
    }

    /**
     * 继承类加载
     * isAssignableFrom 是用来判断一个类和另一个类是否相同或是另一个类的超类或接口
     * @param packageName
     * @param superClass
     * @return
     */
    public List<Class<?>> getClassListBySuper(String packageName, final Class<?> superClass) {
        return new AbstractScanner(packageName) {
            @Override
            public boolean checkAddClass(Class<?> cls) {
                return superClass.isAssignableFrom(cls) && !superClass.equals(cls);
            }
        }.getClassList();
    }
}
